import { computed, inject, reactive, toRef } from 'vue';

export default function (name, { state, getters, actions }) {
  const store = {};

  if (state && typeof state === 'function') {
    const _state = state();
    store.$state = reactive(_state);
    // 把 state 里的所有属性挂载到 store 上
    for (const key in _state) {
      if (Object.hasOwnProperty.call(_state, key)) {
        store[key] = toRef(store.$state, key);
      }
    }
  }

  if (actions && Object.keys(actions).length > 0) {
    for (const key in actions) {
      if (Object.hasOwnProperty.call(actions, key)) {
        store[key] = actions[key];
      }
    }
  }

  if (getters && Object.keys(getters).length > 0) {
    for (const key in getters) {
      store[key] = computed(getters[key].bind(store.$state, store.$state));
      store.$state[key] = store[key];
    }
  }

  return () => {
    const setSubStore = inject('setSubStore');
    const piniaStore = setSubStore(name, reactive(store));
    return piniaStore[name];
  };
}
